<template>
    <view>
        <!-- 公共组件-每个页面必须引入 -->
        <public-module></public-module>
        <wlk-navbar navbarType='5'></wlk-navbar>
        <view class="apply-content relative " v-if="show">
            <image v-if="Config.agent_bg.content" :src="Config.agent_bg.content" class="wd100" mode="widthFix"></image>
            <view class="pd30">
                <u--form
                        labelPosition="left"
                        :model="form"
                        ref="uForm">
                    <block v-for="(item,key) in form">
                        <u-form-item v-if="item.type == 'text'"
                                     labelWidth="80"
                                     borderBottom
                                     :label="key">
                            <u--input
                                    :customStyle="{
                                        padding:'18rpx 0'
                                    }"
                                    v-model="item.info"
                                    clearable
                                    border="none"
                            ></u--input>
                        </u-form-item>
                        <u-form-item
                                v-if="item.type === 'image'"
                                :label="key"
                                label-position="top"
                                labelWidth="auto"
                                borderBottom
                        >
                            <view class="mt20">
                                <u-upload
                                        :fileList="form[key].info"
                                        @afterRead="afterRead"
                                        @delete="deletePic"
                                        :name="key"
                                        multiple
                                        :maxCount="1"
                                        :previewFullImage="true"
                                        accept="image"
                                ></u-upload>
                            </view>

                        </u-form-item>
                    </block>
                </u--form>
            </view>
            <view class="agreement wlkflex justify-center" v-if="Config.agreement.content ==1">
                <view class="icon wlkflex" :style="{borderColor:agreement?themeColor:'#eee'}" @click="agreement = !agreement">
                    <view v-if="agreement">
                        <u-icon name="checkbox-mark" :size="14" :color="themeColor"></u-icon>
                    </view>
                </view>
                <view class="agree-text">我已阅读并遵守</view>
                <view @tap="$Router.push({ path: '/pages/article/detail', query: { id: Config.agreement.value } })" class="protocol" :style="'color: '+themeColor">《服务协议》</view>
            </view>
        </view>
        <u-gap height="100"></u-gap>
        <view class="wlk-fixed-btn">
            <u-button :customStyle="{
                    fontWeight: 'bold',
			        borderRadius:'8px',
			          width:'92%'
                }" :color="themeColor" size="large" @click="submit" text="保存"></u-button>
        </view>
    </view>
</template>
<script>
    var _self;
    import base from '@/base';

    import { mapMutations, mapActions, mapState, mapGetters } from 'vuex';
    export default {
        computed: {
            ...mapGetters(['userInfo','themeColor','isLogin'])
        },
        data() {
            return {
                show:false,
                Config:{},
                form:{
                },
                agreement:false,
            };
        },
        onLoad() {
            _self = this;
        },
        onShow() {
        },
        created(){
            this.getConfig();
        },
        methods: {
            onAgreement(e) {
                this.agreement = e.value;
            },
            getConfig(){
                uni.$u.http.post('commission/getConfig', {
                }).then(res => {
                    this.show = true;
                    this.Config = res.data;
                    let lables = res.data.perfect_form.value.lables;
                    lables.forEach(item=>{
                        if (item.type =='image'){
                            item.info =[];
                        }else{
                            item.info ='';
                        }
                        let b = uni.$u.deepClone(item);
                        _self.form = {
                            ..._self.form,
                            ...{
                                [item.name]: b
                            }
                        };
                    });
                }).catch(res => {
                })
            },
            submit() {
                let valid = true;
                if(this.Config.agreement.content ==1 && !this.agreement){
                    uni.$u.toast('请先阅读并同意协议');
                    return;
                }
                for (const [key, item] of Object.entries(_self.form)) {
                    if (item.rule != 'none') {
                        let res = uni.$u.test[item.rule](item.info);
                        if (!res) {
                            uni.$u.toast(item.name+'数据校验未通过');
                            valid = false;
                            break; // 校验不通过时，停止循环
                        }
                    }
                    if (item.need == 'true' && uni.$u.test.isEmpty(item.info)){
                        uni.$u.toast('请填写'+item.name);
                        valid = false;
                        break; // 校验不通过时，停止循环
                    }
                }

                if (!valid) {
                    return false; // 停止循环后，可以在此处添加逻辑处理
                }
                uni.$u.http.post('commission/apply', {
                    form:_self.form
                }).then(res => {
                    if(this.$Route.query.isPerfect==1){
                        uni.$u.toast('完善成功');
                    }else{
                        uni.$u.toast('申请成功');
                        //  #ifdef MP-WEIXIN
                        try {
                            let typeArr = ['commission'];
                            _self.$store.commit('subScribeMsg', typeArr);
                        } catch (error) {
                            console.error('订阅消息请求失败', error);
                        }
                        //  #endif
                    }
                    setTimeout(()=>{
                        _self.$Router.pushTab('/pages/index/user')
                    },1000)
                }).catch(res => {
                })
            },
            deletePic(event) {
                this.form[event.name].info.splice(event.index, 1)
            },
            // 新增图片
            async afterRead(event) {
                // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
                let lists = [].concat(event.file)
                let fileListLen = this.form[event.name].info.length
                lists.map((item) => {
                    this.form[event.name].info.push({
                        ...item,
                        status: 'uploading',
                        message: '上传中'
                    })
                })
                for (let i = 0; i < lists.length; i++) {
                    const result = await this.uploadFilePromise(lists[i].url);
                    let item = this.form[event.name].info[fileListLen]
                    this.form[event.name].info.splice(fileListLen, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result
                    }))
                    fileListLen++;
                }
            },

            uploadFilePromise(url) {
                let self = this;
                return new Promise((resolve, reject) => {
                    let a = uni.uploadFile({
                        url: base.apiUrl+'common/upload',
                        filePath: url,
                        name: 'file',
                        formData: {
                            user: 'test'
                        },
                        success: (res) => {
                            resolve(JSON.parse(res.data).data.url);
                        }
                    });
                })
            },


        }
    }
</script>
<style lang="scss">
   page{
    .apply-content{
        .agreement{
            padding-top: 50rpx;
            .icon{
                width: 36rpx;
                height: 36rpx;
                border-radius: 36rpx;
                border: 1rpx solid #eee;
                justify-content: center;
            }
            .agree-text{
                padding-left: 10rpx;
                font-size: 26rpx;
                color: #999;
            }
            .and{
                font-size: 26rpx;
                color: #999;
            }
            .protocol{
                font-size: 26rpx;
                color: #999;
            }
        }
    }
       .wlk-fixed-btn{
           box-shadow: 0px -5px 5px rgba(0, 0, 0, 0);
           background-color: transparent;
       }
   }
</style>
